import { TimeRangeSelector } from './components/TimeRangeSelector.js';

// 全局变量
let map;
let locationData = [];
let currentMarker = null;
let pathLine = null;
let playbackTimer = null;
let currentIndex = 0;
let playbackSpeed = 5;
let isPlaying = false;

// 加载高德地图 API
async function loadMapAPI() {
  try {
    await AMapLoader.load({
      key: process.env.AMAP_KEY,
      version: '2.0',
      plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.MapType'],
      AMapUI: {
        version: '1.1',
        plugins: []
      },
      Loca: {
        version: '2.0'
      }
    });
    console.log('地图 API 加载成功');
  } catch (error) {
    console.error('加载地图 API 失败:', error);
    throw error;
  }
}

// 初始化地图
async function initMap() {
  try {
    // 先加载地图 API
    await loadMapAPI();
    
    // 创建地图实例
    map = new AMap.Map('map-container', {
      zoom: 11,
      center: [116.397428, 39.90923]
    });

    // 添加地图控件
    map.addControl(new AMap.Scale());
    map.addControl(new AMap.ToolBar());
    map.addControl(new AMap.MapType());
    
    console.log('地图初始化成功');
  } catch (error) {
    console.error('地图初始化失败:', error);
    throw error;
  }
}

// 加载 Socket.IO
async function loadSocketIO() {
  try {
    const { io } = await import('socket.io-client');
    return io(window.location.origin, {
      path: '/socket.io',
      transports: ['websocket', 'polling'],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000
    });
  } catch (error) {
    console.error('加载 Socket.IO 失败:', error);
    return null;
  }
}

// 初始化事件监听
function initEventListeners() {
  // 查询按钮
  document.getElementById('queryBtn').addEventListener('click', () => {
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    
    if (startTime && endTime) {
      loadHistoricalData(startTime, endTime);
    } else {
      alert('请选择开始和结束时间');
    }
  });
  
  // 播放按钮
  document.getElementById('playBtn').addEventListener('click', startPlayback);
  
  // 暂停按钮
  document.getElementById('pauseBtn').addEventListener('click', pausePlayback);
  
  // 停止按钮
  document.getElementById('stopBtn').addEventListener('click', stopPlayback);
  
  // 速度控制
  document.getElementById('speedControl').addEventListener('input', (e) => {
    playbackSpeed = parseInt(e.target.value);
    document.getElementById('speedValue').textContent = playbackSpeed;
    
    if (isPlaying) {
      pausePlayback();
      startPlayback();
    }
  });
}

// 加载历史数据
async function loadHistoricalData(startTime = null, endTime = null) {
  try {
    let url = '/api/locations';
    if (startTime && endTime) {
      url += `?startTime=${encodeURIComponent(startTime)}&endTime=${encodeURIComponent(endTime)}`;
    }
    console.log('请求URL:', url);

    const response = await fetch(url);
    const data = await response.json();
    console.log('接收到的数据:', data);

    if (data.length === 0) {
      alert('没有找到符合条件的数据');
      return;
    }

    locationData = data;
    console.log('准备显示路径，数据点数量:', locationData.length);
    displayPath();
  } catch (error) {
    console.error('加载历史数据失败:', error);
    alert('加载历史数据失败: ' + error.message);
  }
}

// 显示轨迹路径
function displayPath() {
  console.log('开始显示路径');
  // 清除现有路径
  if (pathLine) {
    console.log('清除现有路径');
    map.remove(pathLine);
  }

  if (locationData.length < 2) {
    console.log('数据点不足，无法绘制路径');
    return;
  }

  // 创建路径点数组
  const path = locationData.map(loc => [loc.longitude, loc.latitude]);
  console.log('路径点数组:', path);

  try {
    // 创建折线
    pathLine = new AMap.Polyline({
      path: path,
      strokeColor: '#3366FF',
      strokeWeight: 6,
      strokeOpacity: 0.8,
      strokeStyle: 'solid',
      lineJoin: 'round',
      showDir: true
    });

    // 添加到地图
    map.add(pathLine);
    console.log('路径已添加到地图');

    // 调整地图视图以显示整个路径
    map.setFitView([pathLine]);
    console.log('地图视图已调整');
  } catch (error) {
    console.error('创建或显示路径时出错:', error);
  }
}

// 更新地图显示
function updateMapDisplay(location) {
  if (!currentMarker) {
    currentMarker = new AMap.Marker({
      position: [location.longitude, location.latitude],
      icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
    });
    map.add(currentMarker);
  } else {
    currentMarker.setPosition([location.longitude, location.latitude]);
  }

  // 更新信息面板
  document.getElementById('current-lat').textContent = location.latitude.toFixed(6);
  document.getElementById('current-lng').textContent = location.longitude.toFixed(6);
  document.getElementById('current-time').textContent = new Date(location.timestamp).toLocaleString();
}

// 开始回放
function startPlayback() {
  if (!locationData.length) return;
  
  isPlaying = true;
  const interval = 1000 / playbackSpeed;
  
  playbackTimer = setInterval(() => {
    if (currentIndex >= locationData.length) {
      stopPlayback();
      return;
    }
    
    updateMapDisplay(locationData[currentIndex]);
    currentIndex++;
  }, interval);
}

// 暂停回放
function pausePlayback() {
  isPlaying = false;
  if (playbackTimer) {
    clearInterval(playbackTimer);
  }
}

// 停止回放
function stopPlayback() {
  pausePlayback();
  currentIndex = 0;
  if (locationData.length > 0) {
    updateMapDisplay(locationData[0]);
  }
}

// 初始化时间选择器
const timeRangeContainer = document.getElementById('time-range-selector');
const timeRangeSelector = new TimeRangeSelector(timeRangeContainer, async (range) => {
  try {
    const params = new URLSearchParams();
    params.append('startTime', range.start);
    params.append('endTime', range.end);
    
    const response = await fetch(`/api/locations?${params}`);
    const data = await response.json();
    
    if (data.length > 0) {
      locationData = data;
      displayPath();
    }
  } catch (error) {
    console.error('获取位置数据失败:', error);
  }
});

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', async () => {
  try {
    // 初始化地图
    await initMap();
    
    // 初始化 Socket.IO 连接
    const socket = await loadSocketIO();
    
    // 添加事件监听
    socket.on('connect', () => {
      console.log('Socket.IO 连接成功, ID:', socket.id);
    });
    
    socket.on('connect_error', (error) => {
      console.error('Socket.IO 连接错误:', error);
    });
    
    socket.on('disconnect', (reason) => {
      console.log('Socket.IO 断开连接:', reason);
    });
    
    socket.on('error', (error) => {
      console.error('Socket.IO 错误:', error);
    });
    
    socket.on('reconnect_attempt', (attemptNumber) => {
      console.log('Socket.IO 尝试重连:', attemptNumber);
    });
    
    socket.on('newLocation', (data) => {
      console.log('收到新位置:', data);
      locationData.push(data);
      updateMapDisplay(data);
    });
    
    // 初始化事件监听
    initEventListeners();
    
    console.log('应用初始化完成');
  } catch (error) {
    console.error('初始化失败:', error);
    alert('应用初始化失败，请检查网络连接和控制台错误信息');
  }
}); 